package com.smart.filter;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smart.entity.LoginUser;
import com.smart.entity.Users;
import com.smart.mapper.UserMapper;
import com.smart.utils.JwtUtils;
import com.smart.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Component
public class JwAuthenticationTokenFilter extends OncePerRequestFilter {

//    @Autowired
//    UserMapper userMapper;

    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            // 放行
            filterChain.doFilter(request,response);
            return;
        }
//        解析token
        String userId;
        try {
            Claims claims = JwtUtils.parseJWT(token);
            userId = claims.getSubject();
//            System.out.println(userId);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
//        从redis中获取用户信息[我直接用了数据库]
//        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("username", "password");
//        queryWrapper.eq("uid",userid);
//        Users users = userMapper.selectOne(queryWrapper);
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);// 从redis中获取用户信息
        System.out.println(loginUser);

        // redis中用户不存在
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("redis中用户不存在!");
        }

//        存入secrityContexHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser , null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        放行
        filterChain.doFilter(request,response);
    }
}
